package com.osc.exam.service.impl;

import com.osc.exam.base.StatusEnum;
import com.osc.exam.dao.UserDao;
import com.osc.exam.entity.domain.Role;
import com.osc.exam.entity.domain.User;
import com.osc.exam.error.AddStuException;
import com.osc.exam.error.CustomerException;
import com.osc.exam.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    /**
     * 登陆功能
     *
     * @param username
     * @param password
     */
    @Override
    public void selectByUserName(String username, String password) {
        // 获取当前用户
        Subject subject = SecurityUtils.getSubject();
        // 封装用户的登陆信息
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        try {
            //
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException e) {
            throw new CustomerException("用户名不存在");
        } catch (AuthenticationException e) {
            throw new CustomerException("账号或密码错误");
        }
    }

    /**
     * 注册功能
     *
     * @param user
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    public void register(User user) {
        int num = userDao.selectByname(user.getUsername());
        if (num != StatusEnum.ZERO.getStatus()){
            throw new AddStuException("该用户已经存在！");
        }
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        int register = userDao.register(user);
        if (register != StatusEnum.ONE.getStatus()){
            throw new AddStuException("注册异常！");
        }
    }

    /**
     * 查询用户的角色信息
     * @param username
     * @return
     */
    @Override
    public User findUserByName(String username) {
        // 获取基本信息
        User user = userDao.selectByUsername(username);
        log.info("获取的用户信息为："+user);
        // 获取用户的角色
        if (!Objects.equals(user, null)) {
            Set<Role> userRole = userDao.getRolesByUserId(Integer.parseInt(user.getRole()));
            // 获取角色带有的权限
            for (Role role:userRole
                 ) {
                role.setPermission(userDao.getPermissionByRoleId(role.getId()));
            }
            user.setRoles(userRole);
        }
        return user;
    }

}
